<?php

declare(strict_types=1);

namespace app\shop\controller;

use app\shop\controller\Base;
use app\model\Column;
use think\facade\Request;
use app\model\Users;
use app\validate\FilesVal;
use think\facade\Filesystem;
use think\exception\ValidateException;
use app\validate\UsersVal;

/**
 * @name 我的
 */
class Mine extends Base
{
    protected $middleware = [\app\shop\middleware\checkToken::class]; //单独使用

    /**
     * @name 获取个人信息
     */
    public function info()
    {
        if (request()->isPost()) {
            $data = request()->token;
            $find = Users::where([['id', '=', $data['id']], ['mobile', '=', $data['mobile']]], 'nickname,sex,email,head_portrait');
            return json(['code' => 0, 'data' => $find]);
        }
    }

    /**
     * @name 保存个人信息
     */
    public function infosave()
    {
        if (request()->isPost()) {
            $data = request()->token;
            $param = Request::param();
            try { //进入验证
                validate(UsersVal::class)->scene('info')->check($param);
            } catch (ValidateException $e) {
                return json(['code' => 1, 'val' => $e->getError()]);
            }
            $res = Users::edit(array_merge($param, $data));
            if ($res) {
                return json(['code' => 0]);
            } else {
                return json(['code' => 2]);
            }
        }
    }

    /**
     * @name 上传头像
     */
    public function infoupload()
    {
        if (request()->isPost()) {
            $files = request()->file('file');
            $data = request()->token;
            $name = rand(0, 999);
            try { //进入验证
                validate(FilesVal::class)->check(['img' => $files]);
                $uploads = Filesystem::disk('public')->putFileAs('files', $files,  $name . "-" . $files->getOriginalName()); //上传文件并加密
                $res = Users::edit(array_merge(['head_portrait' => '/static//' . $uploads], $data));
                if ($res) {
                    return json(['code' => 0, 'src' => '/static//' . $uploads]);
                } else {
                    return json(['code' => 2, 'msg' => '操作失败']);
                }
            } catch (ValidateException $e) {
                return json(['codel' => 1, 'msg' => $e->getError()]);
            }
        }
    }
}
